package com.aponteitor.desktop.event;

import java.lang.reflect.Method;
import java.util.TimerTask;

import com.aponteitor.desktop.Program;

/**
 * @author wellsantos@wellsantos.com
 */
public class BeanActionHandler extends ActionHandler {

    private Object bean;
    private Method method;
        
    public BeanActionHandler(Object bean, String method) {
        setup(bean, method);
    }
    
    public BeanActionHandler(Boolean doubleClick, Object bean, String method) {
        super(doubleClick);
        setup(bean, method);
    }

    public BeanActionHandler(int keyCode, Object bean, String method) {
        super(keyCode);
        setup(bean, method);
    }
    
    private void setup(Object bean, String method) {
        Class<?> type = bean.getClass();
        this.bean = bean;
        try {
            this.method = type.getMethod(method);
            if (!this.method.isAccessible()){
                this.method.setAccessible(true);
            }
        } catch (SecurityException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void run() {
        TimerTask task = new TimerTask() {            
            @Override
            public void run() {
                try {
                    method.invoke(bean);
                } catch (Throwable e) {
                    ExceptionHandler.get().uncaughtException(Thread.currentThread(), e);
                }
            }
        };
        Program.getTimer().schedule(task, 0);
    }

}
